/**************************************************************************
** Qt Creator license header template
**   Special keywords: Programmer 2012/5/10 2012
**   Environment variables: 
**   To protect a percent sign, use '%'.
**************************************************************************/

#include "progressivemeshfilter.h"
#include "progressivemesh.h"

ProgressiveMeshFilter::ProgressiveMeshFilter(QObject *parent) :
    QObject(parent),MeshFilterInterface()
{
    typeList << FP_PM_QUADRIC;// << FP_PM_MID;

    foreach (FilterIDType tt, typeList) {
        actionList << new QAction(filterName(tt),this);
    }
    lastq_QualityThr       = 0.3f;
    lastq_PreserveBoundary = false;
    lastq_PreserveNormal   = false;
    lastq_PreserveTopology = false;
    lastq_OptimalPlacement = true;
    lastq_Selected         = false;
    lastq_PlanarQuadric    = false;
    lastq_QualityWeight    = false;
    lastq_BoundaryWeight   = 1.0;
}

QString ProgressiveMeshFilter::filterName(FilterIDType filter) const
{
    switch(filter){
    case FP_PM_QUADRIC: return tr("Progressive Mesh (Quadric)");
    default: assert(0);
    }
    return tr("");
}

QString ProgressiveMeshFilter::filterInfo(FilterIDType filter) const
{
    switch(filter){
    case FP_PM_QUADRIC: return tr("generating the pm representation of model based on quadric simplification,Two other files will be created in the same directory with model file");
    default: assert(0);
    }
    return tr("");
}

MeshFilterInterface::FilterClass ProgressiveMeshFilter::getClass(QAction *a)
{
    switch(ID(a)){
    case FP_PM_QUADRIC: return MeshFilterInterface::Camera;
    default: assert(0);
    }
    return MeshFilterInterface::Generic;
}

int ProgressiveMeshFilter::getPreConditions(QAction *a) const
{
    switch(ID(a)){
    case FP_PM_QUADRIC: return MeshModel::MM_FACENUMBER;
    default: assert(0);
    }
    return MeshModel::MM_NONE;
}

void ProgressiveMeshFilter::initParameterSet(QAction *a, MeshModel &m, RichParameterSet &parlst)
{
    switch(ID(a)){
    case FP_PM_QUADRIC:
        parlst.addParam(new RichInt  ("TargetFaceNum", (m.cm.sfn>0) ? m.cm.sfn/2 : m.cm.fn/2,"Target number of faces", "The desired final number of faces."));
        parlst.addParam(new RichFloat("TargetPerc", 0,"Percentage reduction (0..1)", "If non zero, this parameter specifies the desired final size of the mesh as a percentage of the initial size."));
        parlst.addParam(new RichFloat("QualityThr",lastq_QualityThr,"Quality threshold","Quality threshold for penalizing bad shaped faces.<br>The value is in the range [0..1]\n 0 accept any kind of face (no penalties),\n 0.5  penalize faces with quality < 0.5, proportionally to their shape\n"));
  parlst.addParam(new RichBool ("PreserveBoundary",lastq_PreserveBoundary,"Preserve Boundary of the mesh","The simplification process tries to do not affect mesh boundaries during simplification"));
  parlst.addParam(new RichFloat("BoundaryWeight",lastq_BoundaryWeight,"Boundary Preserving Weight","The importance of the boundary during simplification. Default (1.0) means that the boundary has the same importance of the rest. Values greater than 1.0 raise boundary importance and has the effect of removing less vertices on the border. Admitted range of values (0,+inf). "));
        parlst.addParam(new RichBool ("PreserveNormal",lastq_PreserveNormal,"Preserve Normal","Try to avoid face flipping effects and try to preserve the original orientation of the surface"));
  parlst.addParam(new RichBool ("PreserveTopology",lastq_PreserveTopology,"Preserve Topology","Avoid all the collapses that should cause a topology change in the mesh (like closing holes, squeezing handles, etc). If checked the genus of the mesh should stay unchanged."));
        parlst.addParam(new RichBool ("OptimalPlacement",lastq_OptimalPlacement,"Optimal position of simplified vertices","Each collapsed vertex is placed in the position minimizing the quadric error.\n It can fail (creating bad spikes) in case of very flat areas. \nIf disabled edges are collapsed onto one of the two original vertices and the final mesh is composed by a subset of the original vertices. "));
        parlst.addParam(new RichBool ("PlanarQuadric",lastq_PlanarQuadric,"Planar Simplification","Add additional simplification constraints that improves the quality of the simplification of the planar portion of the mesh."));
        parlst.addParam(new RichBool ("QualityWeight",lastq_QualityWeight,"Weighted Simplification","Use the Per-Vertex quality as a weighting factor for the simplification. The weight is used as a error amplification value, so a vertex with a high quality value will not be simplified and a portion of the mesh with low quality values will be aggressively simplified."));
        parlst.addParam(new RichBool ("AutoClean",true,"Post-simplification cleaning","After the simplification an additional set of steps is performed to clean the mesh (unreferenced vertices, bad faces, etc)"));
        parlst.addParam(new RichBool ("Selected",m.cm.sfn>0,"Simplify only selected faces","The simplification is applied only to the selected set of faces.\n Take care of the target number of faces!"));
        break;
    default: assert(0);
    }
}

bool ProgressiveMeshFilter::applyFilter(QAction *filter, MeshDocument &md, RichParameterSet &par, vcg::CallBackPos *cb)
{
    MeshModel& m = *md.mm();
    switch(ID(filter)){
    case FP_PM_QUADRIC:{
        m.updateDataMask(MeshModel::MM_VERTFACETOPO|MeshModel::MM_FACEFLAGBORDER|MeshModel::MM_VERTMARK);
        int TargetFaceNum = par.getInt("TargetFaceNum");
        if(par.getFloat("TargetPerc")!=0) TargetFaceNum = m.cm.fn*par.getFloat("TargetPerc");

        ProgressiveMeshParameter pp;
        pp.QualityThr=lastq_QualityThr =par.getFloat("QualityThr");
        pp.PreserveBoundary=lastq_PreserveBoundary = par.getBool("PreserveBoundary");
        pp.BoundaryWeight = pp.BoundaryWeight * par.getFloat("BoundaryWeight");
        pp.PreserveTopology=lastq_PreserveTopology = par.getBool("PreserveTopology");
        pp.QualityWeight=lastq_QualityWeight = par.getBool("QualityWeight");
        pp.NormalCheck=lastq_PreserveNormal = par.getBool("PreserveNormal");
        pp.OptimalPlacement=lastq_OptimalPlacement = par.getBool("OptimalPlacement");
        pp.QualityQuadric=lastq_PlanarQuadric = par.getBool("PlanarQuadric");
        lastq_Selected = par.getBool("Selected");

        simplify(m.cm,TargetFaceNum,lastq_Selected,pp,cb);

        Sleep(5000);

        restore(m.cm,pp,cb,m.fullName().toStdString());

        if(par.getBool("AutoClean"))
        {
            int nullFaces=vcg::tri::Clean<CMeshO>::RemoveFaceOutOfRangeArea(m.cm,0);
            if(nullFaces) Log( "PostSimplification Cleaning: Removed %d null faces", nullFaces);
            int deldupvert=vcg::tri::Clean<CMeshO>::RemoveDuplicateVertex(m.cm);
            if(deldupvert) Log( "PostSimplification Cleaning: Removed %d duplicated vertices", deldupvert);
            int delvert=vcg::tri::Clean<CMeshO>::RemoveUnreferencedVertex(m.cm);
            if(delvert) Log( "PostSimplification Cleaning: Removed %d unreferenced vertices",delvert);
            m.clearDataMask(MeshModel::MM_FACEFACETOPO | MeshModel::MM_FACEFLAGBORDER);
            vcg::tri::Allocator<CMeshO>::CompactVertexVector(m.cm);
            vcg::tri::Allocator<CMeshO>::CompactFaceVector(m.cm);
        }

        vcg::tri::UpdateNormals<CMeshO>::PerVertexNormalizedPerFace(m.cm);
        vcg::tri::UpdateBounding<CMeshO>::Box(m.cm);

        break;}//end case FP_PM_QUADRIC
    }
    return true;
}

Q_EXPORT_PLUGIN(ProgressiveMeshFilter)
